//
//  NSString+Helper.m
//  Kaagad Peso
//
//  Created by ZhengChengFeng on 2024/10/15.
//

#import "NSString+Helper.h"

@implementation NSString (Helper)

+ (CGSize)textSizeWithText:(NSString *)textStr font:(UIFont*)font numberOfLines:(NSInteger)numberOfLines lineSpacing:(CGFloat)lineSpacing constrainedWidth:(CGFloat)constrainedWidth{
    if (textStr.length == 0) {
        return CGSizeZero;
    }
    CGFloat oneLineHeight = font.lineHeight;
    CGSize textSize = [textStr boundingRectWithSize:CGSizeMake(constrainedWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil].size;
    CGFloat rows = textSize.height / oneLineHeight;
    CGFloat realHeight = oneLineHeight;
    if (numberOfLines == 0) {
        if (rows >= 1) {
            realHeight = (rows * oneLineHeight) + (rows - 1) * lineSpacing;
        }
    } else {
        if (rows > numberOfLines) {
            rows = numberOfLines;
                }
        realHeight = (rows * oneLineHeight) + (rows - 1) * lineSpacing;
    }
    return CGSizeMake(textSize.width, realHeight);
}

+ (NSAttributedString*)setText:(NSString*)text lineSpacing:(CGFloat)lineSpace font:(UIFont*)font withAlignment:(NSTextAlignment)alignment{
    if (text.length<=0) {
        return nil;
    }
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpace;
    paragraphStyle.alignment = alignment;
    paragraphStyle.lineBreakMode = NSLineBreakByTruncatingTail;
    NSDictionary *attrsDictionary =@{
        NSFontAttributeName: font,
        NSParagraphStyleAttributeName:paragraphStyle
    };
    
    return [[NSAttributedString alloc]initWithString:text attributes:attrsDictionary];
}

+ (NSString* )starsReplacedOfString:(NSString *)str withinRange:(NSRange)range{
    if (str == nil || [str length]< range.location + range.length){
        return str;
    }
    
    NSMutableString* mStr = [[NSMutableString alloc]initWithString:str];
    [mStr replaceCharactersInRange:range withString:[[NSString string] stringByPaddingToLength:range.length withString: @"*" startingAtIndex:0]];
    return mStr;
}

+ (void)callTelPhoneNo:(NSString*)telNo{
    if  (PMStringIsEmpty(telNo)) return ;
    NSString * callPhoneUrl =[NSString stringWithFormat:@"tel://%@",telNo];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhoneUrl] options:@{} completionHandler:^(BOOL success) {}];
}

+ (NSString *)currentDateWithFormat:(NSString *)format {
    
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
    
    NSDate* date = [NSDate date];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}

+ (NSString *)getNowTimeTimestamp:(NSString *)format{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format];
   
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];
    NSDate *confromTimespNow = [NSDate dateWithTimeIntervalSince1970:[datenow timeIntervalSince1970]];
    
    NSString *timeSp = [NSString stringWithFormat:@"%lld", (long long)([confromTimespNow timeIntervalSince1970])];//*1000
    
    return timeSp;
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    if(error) {
        return nil;
    }
    return dic;
}

+ (NSData *)dictionaryToData:(NSDictionary *)dicJson{
    if (![dicJson isKindOfClass:[NSDictionary class]]) {
        return nil;
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dicJson options:0 error:nil];
    if (![jsonData isKindOfClass:[NSData class]]) {
        return nil;
    }
    return jsonData;
}

+ (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    NSString *base64String = [[jsonData base64EncodedStringWithOptions:0] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    return base64String;
//    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

+ (NSDictionary *)getObjectData:(id)obj{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    unsigned int propsCount;
    objc_property_t *props =class_copyPropertyList([obj class], &propsCount);
    for(int i =0;i < propsCount; i++)
    {
        objc_property_t prop = props[i];
        
        NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
        id value = [obj valueForKey:propName];
        if(value ==nil)
        {
            value = [NSNull null];
        }
        else
        {
            value = [self getObjectInternal:value];
        }
        [dic setObject:value forKey:propName];
    }
    return dic;
}

+ (id)getObjectInternal:(id)obj{
    
    if([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[NSNumber class]] || [obj isKindOfClass:[NSNull class]]){
        return obj;
    }
    if([obj isKindOfClass:[NSArray class]]){
        NSArray *objarr = obj;
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
        for(int i =0;i < objarr.count; i++){
            
            [arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]]atIndexedSubscript:i];
        }
        return arr;
    }
    
    if([obj isKindOfClass:[NSDictionary class]]){
        NSDictionary *objdic = obj;
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
        for(NSString *key in objdic.allKeys){
            [dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];
        }
        return dic;
    }
    return [self getObjectData:obj];
}



- (NSMutableDictionary *)getURLParameters {
    
   
    NSRange range = [self rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
   
    NSString *parametersString = [self substringFromIndex:range.location + 1];
    
   
    if ([parametersString containsString:@"&"]) {
        
       
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
          
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
           
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                
                if ([existValue isKindOfClass:[NSArray class]]) {
                    
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
            
                [params setValue:value forKey:key];
            }
        }
    } else {
     
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
      
        if (pairComponents.count == 1) {
            return nil;
        }
        
      
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
     
        if (key == nil || value == nil) {
            return nil;
        }
        

        [params setValue:value forKey:key];
    }
    
    return params;
}

+ (CAShapeLayer *)UIBezierPathWithRect:(CGRect)rect withCorners:(UIRectCorner)corners withRadiu:(CGSize)cornerRadiu{
    UIBezierPath *maskPathAdV = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corners cornerRadii:cornerRadiu];
    CAShapeLayer *maskLayerAdv = [[CAShapeLayer alloc] init];
    maskLayerAdv.frame = rect;
    maskLayerAdv.path = maskPathAdV.CGPath;
    return maskLayerAdv;
}

+ (NSString *)countNumForThreeformat:(NSString *)numStr{
    if (PMStringIsEmpty(numStr)) {
        return @"--";
    }
    NSString* str11;
    NSString* str22;
    
    if ([numStr containsString:@"."]) {
        NSArray* array = [numStr componentsSeparatedByString:@"."];
        str11 = array[0];
        str22 = array[1];
    }else{
        str11 = numStr;
    }
    
    int count = 0;
    long long int a = str11.longLongValue;
    while (a != 0)
    {
        count++;
        a /= 10;
    }
    NSMutableString *string = [NSMutableString stringWithString:str11];
    NSMutableString *newString = [NSMutableString string];
    while (count > 3) {
        count -= 3;
        NSRange rang = NSMakeRange(string.length - 3, 3);
        NSString *str = [string substringWithRange:rang];
        [newString insertString:str atIndex:0];
        [newString insertString:@"," atIndex:0];
        [string deleteCharactersInRange:rang];
    }
    [newString insertString:string atIndex:0];
    
    if ([numStr containsString:@"."]) {
        
        NSString* str33;
        
        if (str22.length>0) {
            str33 = [NSString stringWithFormat:@"%@.%@",newString,str22];
        }
        else{
            str33 = [NSString stringWithFormat:@"%@",newString];
        }
        return str33;
        
    }else{
        return newString;
    }
}

@end
